//
//  JKDownLoaderManger.m
//  JKDownLoader
//
//  Created by 王冲 on 2019/2/9.
//  Copyright © 2019年 JK科技有限公司. All rights reserved.
//

#import "JKDownLoaderManger.h"
#import "NSString+JK_MD5.h"
@interface JKDownLoaderManger ()

@property(nonatomic,strong) JKDownLoader *downLoader;

// 创建一个下载操作的缓存池
@property(nonatomic,strong) NSMutableDictionary <NSString *, JKDownLoader *>*downloadCache;

@end

@implementation JKDownLoaderManger

static id instance;

/**
 单利：
     1.无论通过怎样的方式，创建出来，只有一个实例（alloc,new,muableCopy）
     2.通过某种方式，可以获取同一个对象，但是也开通过其他方式，创建出来新的对象
 */
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    
    return instance;
}

-(id)copy{
    
    return instance;
}

-(id)mutableCopy{
    
    return instance;
}

+(instancetype)shareDownloaderManger{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc]init];
    });
    
    return instance;
}

// key： MD5的url地址  value： JKDownLoader 对象
-(NSMutableDictionary *)downloadCache{
    
    if (!_downloadCache) {
        _downloadCache = [[NSMutableDictionary alloc]init];
    }
    return _downloadCache;
}

#pragma mark 下载
-(void)jk_downLoader:(NSURL *)url withDownInfo:(downLoadInfoBlock)downInfo withProgress:(downLoadProgressChange)progress withdownLoadStateChangeType:(downLoadStateChangeTypeBlock)stateType withSuccess:(downLoadSuccessBlock)success withFail:(downLoadFailBlock)fail{
    
    self.fail = fail;
    
    // 1.取的url的MD5值
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    
    // 2.根据url的md5，查找相应的下载器，每个下载器就是一个JKDownLoader
    JKDownLoader *downLoader = self.downloadCache[md5String];
    
    if (downLoader != nil) {
        NSLog(@"已经在下载列表中，请不要重复下载");
        if (self.fail) {
            self.fail(@"已经在下载列表中，请不要重复下载");
        }
        return;
    }
    
    downLoader = [[JKDownLoader alloc]init];
    self.downloadCache[md5String] = downLoader;

    __weak typeof(self) weakSelf = self;
    [downLoader jk_downLoader:url withDownInfo:downInfo withProgress:progress withdownLoadStateChangeType:stateType withSuccess:^(NSString * _Nonnull cachePath) {

        // 1.将下载从缓存池移除
        [weakSelf.downloadCache removeObjectForKey:md5String];
        // 2.执行调用方法的回调
        if (success) {
            
            success(cachePath);
        }
    } withFail:^(NSString * _Nonnull errorMessage) {
        
        [weakSelf.downloadCache removeObjectForKey:md5String];
        
        if (self.fail) {
            
            self.fail(errorMessage);
        }
    }];
}

    
-(JKDownLoader *)downLoadWithURL: (NSURL *)url
{

    // 1.取的url的MD5值
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    
    // 2.根据url的md5，查找相应的下载器，每个下载器就是一个JKDownLoader
    JKDownLoader *downLoader = self.downloadCache[md5String];
    
    if (downLoader != nil) {
        [downLoader jk_resumeCurrentTask];
        return downLoader;
    }
    
    downLoader = [[JKDownLoader alloc]init];
    self.downloadCache[md5String] = downLoader;
    
    __weak typeof(self) weakSelf = self;
    
    [downLoader jk_downLoader:url withDownInfo:^(long long totalSize, NSString * _Nonnull cachePath) {
        
    } withProgress:^(float progress) {
        
    } withdownLoadStateChangeType:^(JKDownLoaderState state) {
        
    } withSuccess:^(NSString * _Nonnull cachePath) {
        
        // 1.将下载从缓存池移除
        [weakSelf.downloadCache removeObjectForKey:md5String];
        
    } withFail:^(NSString * _Nonnull errorMessage) {
        //
        [weakSelf.downloadCache removeObjectForKey:md5String];
    }];
    
    return downLoader;

}

#pragma mark 暂停某个文件下载

/**
 暂停当前的下载任务
 
 @param url 暂停资源的url
 */
-(void)pauseLoadWithUrl:(NSURL *)url{
    
    // 1.取的url的MD5值
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    JKDownLoader *downLoader = self.downloadCache[md5String];
    
    // 2.暂停下载
    if (downLoader == nil){
        
        if (self.fail) {
            
            self.fail(@"已经暂停下载，请不要重复点击");
        }
        return;
    }
    
    [downLoader jk_pauseCurrentTask];
    
    // 3.从缓存池移除
    [self.downloadCache removeObjectForKey:md5String];
}

#pragma mark 取消当前的下载任务
/**
 取消当前的下载任务
 
 @param url 暂停资源的url
 */
-(void)cancelLoadWithUrl:(NSURL *)url{
    
    // 1.取的url的MD5值
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    JKDownLoader *downLoader = self.downloadCache[md5String];
    [downLoader jk_cancelCurrentTask];
}
    
#pragma mark 取消并清理当前的下载任务
/**
 取消并清理当前的下载任务
 
 @param url 暂停资源的url
 */
-(void)cancelAndCleanLoadWithUrl:(NSURL *)url{
    
}

#pragma mark 继续某个文件下载
/**
 继续某个文件下载
 
 @param url 暂停资源的url
 */
-(void)resumeLoadWithUrl:(NSURL *)url{
    
    // 1.取的url的MD5值
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    JKDownLoader *downLoader = self.downloadCache[md5String];
    [downLoader jk_resumeCurrentTask];
}

#pragma mark 暂停全部文件下载
/**
 暂停全部文件下载
 */
-(void)pauseAllDownLoad{
    
    [self.downloadCache.allValues performSelector:@selector(jk_pauseCurrentTask) withObject:nil];
}

#pragma mark 开始全部文件下载
/**
 开始全部文件下载
 */
-(void)startAllDownLoad{
    
    [self.downloadCache.allValues performSelector:@selector(jk_resumeCurrentTask) withObject:nil];
}

#pragma mark 获取当前url对应的 DownLoader
- (JKDownLoader *)getDownLoaderWithURL:(NSURL *)url {
    
    NSString *md5String = [NSString jk_MD5ForLower32Bate:url.absoluteString];
    JKDownLoader *downLoader = self.downloadCache[md5String];
    return downLoader;
}

@end
